package com.xiaoq.push.service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.xiaomi.xmpush.server.Constants;
import com.xiaomi.xmpush.server.Message;
import com.xiaomi.xmpush.server.Message.Builder;
import com.xiaomi.xmpush.server.Message.IOSBuilder;
import com.xiaomi.xmpush.server.Result;
import com.xiaomi.xmpush.server.Sender;
import com.xiaoq.coms.util.BeanToMapUtils;
import com.xiaoq.push.vo.MessageSenderVo;

@Service
public class MiPushServerService {

	private static final Logger LOG = LoggerFactory.getLogger(MiPushServerService.class);

	private final String APP_SECRET_IOS = "gkX1WRYY+z3bt2ASLWDGXA==";

	private final String APP_SECRET_ANDROID = "QQIH1+MXDqU4LpSbwj3c8A==";

	private final String PACKAGE_NAME_ANDROID = "com.xiaoq";
	
	@Value("${xiaomi.environment}")
	private String environment;

	public String sendMessageToMultiAndroidUsers(MessageSenderVo messageSerderVo, List<String> regIds)
			throws Exception {

		Constants.useOfficial();

		Sender sender = new Sender(APP_SECRET_ANDROID);

		LOG.debug("regIds = " + regIds.toString());

		Message message = createAndroidMessage(messageSerderVo);

		Result result = sender.send(message, regIds, 3); // 发送消息到一组设备上,
															// regids个数不得超过1000个

		if (result != null) {
			LOG.debug("data = " + result.toString() + ", msgId = " + result.getMessageId());

			return result.getMessageId();
		}
		return null;
	}
	
	public String sendMessageToMultiIOSUsers(MessageSenderVo messageSerderVo, List<String> regIds) throws Exception {
		if("test".equals(environment)){
			Constants.useSandbox(); 
		}else{
			Constants.useOfficial();
		}
		Sender sender = new Sender(APP_SECRET_IOS);

		LOG.debug("regIds = " + regIds.toString());

		Message message = createIOSMessage(messageSerderVo);

		try {

			Result result = sender.send(message, regIds, 3); // 发送消息到一组设备上,
																// regids个数不得超过1000个

			if (result != null) {
				LOG.debug("data = " + result.toString() + ", msgId = " + result.getMessageId());

				return result.getMessageId();
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return null;
	}
	  
	  /**
	   * 按着系统原型设计的一个比较有局限性的发送android用户消息
	   * @param catalogueCode
	   * @param msgCatalogueName
	   * @param msgTitle
	   * @param msgThumbnailUrl
	   * @param msgContent
	   * @param regIds
	   * @return
	   * @throws Exception
	   */
	  public String sendMessageToSingleAndroidUser(MessageSenderVo messageSerderVo,String regId) throws Exception {

			Constants.useOfficial();

			Sender sender = new Sender(APP_SECRET_ANDROID);

			LOG.debug("regId = " + regId);

			Message message = createAndroidMessage(messageSerderVo);

			Result result = sender.send(message, regId, 3); // 发送消息到一组设备上,
																// regids个数不得超过1000个

			if (result != null) {
				LOG.debug("data = " + result.toString() + ", msgId = " + result.getMessageId());

				return result.getMessageId();
			}
			return null;
		}
	  
	  /**
	   * 根据原型设计出来的发送iOS用户消息
	   * @param catalogueCode
	   * @param msgCatalogueName
	   * @param msgTitle
	   * @param msgThumbnailUrl
	   * @param msgContent
	   * @param regIds
	   * @return
	   * @throws Exception
	   */
	public String sendMessageToSingleIOSUser(MessageSenderVo messageSerderVo, String regId) throws Exception {

		if ("test".equals(environment)) {
			Constants.useSandbox();
		} else {
			Constants.useOfficial();
		}
		Sender sender = new Sender(APP_SECRET_IOS);

		LOG.debug("regId = " + regId);

		Message message = createIOSMessage(messageSerderVo);

		try {

			Result result = sender.send(message, regId, 3); // 发送消息到一组设备上,
															// regids个数不得超过1000个

			if (result != null) {
				LOG.debug("data = " + result.toString() + ", msgId = " + result.getMessageId());

				return result.getMessageId();
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return null;
	}
	  
	@SuppressWarnings("rawtypes")  
	private Message createIOSMessage(MessageSenderVo messageSenderVo) {
		String description = messageSenderVo.getMsgContent();
		IOSBuilder builder = new Message.IOSBuilder().description(description).soundURL("default") // 消息铃声
				.badge(1)// 数字角标
				.category("action")
//				.extra("content-available", "1")
				.extra("notify_foreground", "0")
				.extra(Constants.EXTRA_PARAM_NOTIFY_FOREGROUND, "0")
				 .extra(Constants.EXTRA_PARAM_NOTIFY_EFFECT, Constants.NOTIFY_LAUNCHER_ACTIVITY)
				.extra("flow_control", "3000")   // 设置平滑推送, 推送速度4000每秒(qps=4000)
                .extra("pubTime", System.currentTimeMillis()+"");

		Map messageMapper = BeanToMapUtils.toMap(messageSenderVo);
		Set messageSet = messageMapper.keySet();

		Iterator iterator = messageSet.iterator();
		while (iterator.hasNext()) {
			String extraKey = (String) iterator.next();
			if(messageMapper.get(extraKey)!=null){
				String extraValue = (String) messageMapper.get(extraKey);
				builder.extra(extraKey, extraValue);
			}
		}
		return builder.build();
	}
	  
	  
	@SuppressWarnings("rawtypes")
	private Message createAndroidMessage(MessageSenderVo messageSenderVo) {
		String title = messageSenderVo.getMsgTitle();
		String description = messageSenderVo.getMsgContent();
		Builder builder = new Message.Builder().title(title).description(description).payload(title)
				.restrictedPackageName(PACKAGE_NAME_ANDROID).notifyType(1) // 使用默认提示音提示
				.extra("flow_control", "4000")   // 设置平滑推送, 推送速度4000每秒(qps=4000)
                .extra("pubTime", System.currentTimeMillis()+"");
		Map messageMapper = BeanToMapUtils.toMap(messageSenderVo);
		Set messageSet = messageMapper.keySet();

		Iterator iterator = messageSet.iterator();
		while (iterator.hasNext()) {
			String extraKey = (String) iterator.next();
			if(messageMapper.get(extraKey)!=null){
				String extraValue = (String) messageMapper.get(extraKey);
				builder.extra(extraKey, extraValue);
			}
		}
		return builder.build();
	}

}
